package controller;

import pojo.Cart;
import pojo.Goods;
import service.ICartService;
import service.IGoodsService;
import service.IUserService;
import service.impl.CartServiceImpl;
import service.impl.GoodsServiceImpl;
import service.impl.UserServiceImpl;
import utils.NoLoginUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "CartServlet", value = "/cart")
public class CartServlet extends HttpServlet {
    private ICartService cartService;
    private IUserService userService;
    private IGoodsService goodsService;

    @Override
    public void init() throws ServletException {
        cartService = new CartServiceImpl();
        userService = new UserServiceImpl();
        goodsService = new GoodsServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        NoLoginUtil.doVerify(request);
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        if (username != null) {
            int uid = userService.queryIdByUsername(username);
            List<Cart> cartList = cartService.queryByUid(uid);
            List<Goods> goodsList = new ArrayList<>();
            List<Integer> countList = new ArrayList<>();
            for (Cart cart : cartList) {
                countList.add(cart.getG_count());
                goodsList.add(goodsService.queryGoodsById(cart.getGid()));
            }
            request.setAttribute("cartList", cartList);
            request.setAttribute("goodsList", goodsList);
            request.setAttribute("countList", countList);
        }
        request.getRequestDispatcher("/WEB-INF/cart.jsp").forward(request, response);
    }
}
